package com.forrest.user.edit;

import com.forrest.common.interceptor.GenderInterceptor;
import com.forrest.common.interceptor.UserInterceptor;
import com.forrest.common.model.User;
import com.forrest.login.LoginService;
import com.forrest.user.index.UserService;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;

import java.io.File;

public class UserEditController extends Controller {

    private static final UserService srv = UserService.me;

    @Before({UserInterceptor.class, GenderInterceptor.class})
    public void index() {
        render("index.html");
    }

    public void avator() {
        UploadFile uploadFile = getFile("avator", "/userimg");
        User user = LoginService.me.validateToken(getCookie(LoginService.USER));
        File file = uploadFile.getFile();
        String rename = user.getUsername() + uploadFile.getFileName();
        File file1 = new File(file.getParent(), "/" + rename);
        if (!file.renameTo(file1)) {
            renderJson(Ret.by("status", false).set("msg", "上传错误"));
        } else {
            renderJson(srv.avator(user, rename));
        }
    }

    public void update(String pname, String gender, String phone, String company, String address) {
        User user = LoginService.me.validateToken(getCookie(LoginService.USER));
        renderJson(srv.update(user, pname, gender, phone, company, address));
    }

}
